﻿namespace Jerky.Helper;

/// <summary>
/// ZIP帮助类
/// </summary>
/// <remarks>用于压缩和解压缩文件</remarks>
static class ZipHelper
{
    /// <summary>
    /// 打开一个ZIP包
    /// </summary>
    /// <param name="filePath">ZIP文件路径</param>
    /// <param name="fileMode">文件模式</param>
    /// <returns>Package对象</returns>
    public static Package OpenPackage(string filePath, FileMode fileMode)
    {
        return Package.Open(filePath, fileMode);
    }

    /// <summary>
    /// 获取ZIP包中的部件
    /// </summary>
    /// <param name="package">Package对象</param>
    /// <param name="partUri">部件的URI</param>
    /// <returns>PackagePart对象</returns>
    public static PackagePart GetPackagePart(Package package, string partUri)
    {
        return package.GetPart(new Uri(partUri, UriKind.Relative));
    }

    /// <summary>
    /// 读取ZIP包中部件的内容
    /// </summary>
    /// <param name="packagePart">PackagePart对象</param>
    /// <returns>部件的内容</returns>
    public static string ReadPackagePartContent(PackagePart packagePart)
    {
        using var reader = new StreamReader(packagePart.GetStream());

        return reader.ReadToEnd();
    }

    /// <summary>
    /// 写入内容到ZIP包中的部件
    /// </summary>
    /// <param name="packagePart">PackagePart对象</param>
    /// <param name="content">要写入的内容</param>
    public static void WritePackagePartContent(PackagePart packagePart, string content)
    {
        using var writer = new StreamWriter(packagePart.GetStream(FileMode.Create, FileAccess.Write));
        
        writer?.Write(content);
    }

    /// <summary>
    /// 异步ZIP包中部件的内容
    /// </summary>
    /// <param name="packagePart">PackagePart对象</param>
    /// <returns>部件的内容</returns>
    public static async Task<string> ReadPackagePartContentAsync(PackagePart packagePart)
    {
        using var reader = new StreamReader(packagePart.GetStream());
        return await reader.ReadToEndAsync();
    }

    /// <summary>
    /// 异步写入内容到ZIP包中的部件
    /// </summary>
    /// <param name="packagePart">PackagePart对象</param>
    /// <param name="content">要写入的内容</param>
    public static async Task WritePackagePartContentAsync(PackagePart packagePart, string content)
    {
        using var writer = new StreamWriter(packagePart.GetStream(FileMode.Create, FileAccess.Write));
        await writer.WriteAsync(content);
    }

    /// <summary>
    /// 关闭ZIP包
    /// </summary>
    /// <param name="package">Package对象</param>
    public static void ClosePackage(Package package)
    {
        package.Close();
    }
}
